package com.gxa.global.jwt;

import com.alibaba.fastjson.JSONObject;
import com.gxa.common.JwtResult;
import com.gxa.common.R;
import com.gxa.utils.JwtUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截token
 */
public class JwtInterceptor implements HandlerInterceptor{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String token = request.getHeader("Authorization"); //从前端header中获取token
        System.out.println(token);
        //设置响应的类型为json
        response.setContentType("application/json;charset=utf-8");
        R r = new R();
        if(token == null || "".equals(token)){
            r.setCode(500);
            r.setMsg("请登录");
            response.getWriter().write(JSONObject.toJSONString(r));
            response.getWriter().flush();
            response.getWriter().close();
            return false;
        }
        JwtResult jwtResult = JwtUtils.validateJwt(token);
        if(jwtResult.isSuccess()){
            // 验证通过
            return true;
        }else{
            r.setCode(jwtResult.getErrCode());
            r.setMsg("token 验证失败！");
            response.getWriter().write(JSONObject.toJSONString(r));
            response.getWriter().flush();
            response.getWriter().close();
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
